/**
 * 
 */
package com.miolr.module.core.social;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.Connection;

import com.couponornot.social.weibo.api.Tweet;
import com.couponornot.social.weibo.api.Weibo;
import com.couponornot.social.weibo.connect.v2.WeiboConnectionFactory;
import com.miolr.module.core.model.Message;
import com.miolr.module.core.model.SocialConnection;
import com.miolr.module.core.model.User;
import com.miolr.module.core.service.MessageService;
import com.miolr.module.core.service.SocialConnectionService;
import com.miolr.module.core.service.UserService;

/**
 * @author iday
 * 
 */
@Named
public class WeiboMessageAdapter implements SocialMessageImporter {

	public static final String PROVIDER_ID = "weibo";

	@Inject
	private WeiboConnectionFactory factory;
	@Inject
	private SocialConnectionService connectionService;
	@Inject
	private TextEncryptor textEncryptor;
	@Inject
	private MessageService messageService;
	@Inject
	private UserService userService;

	@Override
	public void importMessage(String userId) {
		SocialConnection connection = this.connectionService.findByUserId(
				PROVIDER_ID, userId).get(0);
		Connection<Weibo> conn = this.factory.createConnection(connection
				.getData(this.textEncryptor));
		conn.refresh();
		User user = this.userService.loadUserByUsername(userId);
		Message lastMessage = this.messageService.getLastMessage(PROVIDER_ID,
				user);
		String lastid = "0";
		if (lastMessage != null) {
			lastid = lastMessage.getSourceId();
		}
		List<Tweet> tweets = conn.getApi().timelineOperations()
				.getHomeTimeline(Long.valueOf(lastid), 0, 200, 1, 0, 1);
		List<Message> messages = new ArrayList<>(tweets.size());
		for (Tweet tweet : tweets) {
			Message message = new Message();
			message.setTitle(tweet.getText());
			message.setImg(tweet.getBmiddlePic());
			message.setSource(PROVIDER_ID);
			message.setCreated(tweet.getCreatedAt());
			message.setUrl(conn.getProfileUrl() + "/" + tweet.getId());
			messages.add(message);
		}
		if (!messages.isEmpty()) {
			messageService.saveOrUpdate(messages);
		}
	}
}
